﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace VerticalSpiderEditor
{
    public static class XmlExtend
    {
        public static XmlNode AddChildNode(this XmlDocument @this, string name, string value = null)
        {
            var node = @this.AppendChild(@this.CreateElement(name));

            if (string.IsNullOrEmpty(value) == false)
                node.AppendChild(@this.CreateTextNode(value));

            return node;
        }

        public static XmlNode AddChildNode(this XmlNode @this, string name, string value = null)
        {
            var node = @this.AppendChild(@this.OwnerDocument.CreateElement(name));

            if (string.IsNullOrEmpty(value) == false)
                node.AppendChild(@this.OwnerDocument.CreateTextNode(value));

            return node;
        }

        public static XmlNode GetOrCreateNode(this XmlNode @this, string childNodeName)
        {
            var childNode = @this.SelectSingleNode($"./{childNodeName}");
            if (childNode == null)
                childNode = @this.AddChildNode(childNodeName);

            return childNode;
        }
    }
}
